#include <unistd.h>
#include <iostream>
#include <stdlib.h>
#include <pthread.h>
#include <stdio.h>
#include<time.h>
#include "Get_Matrix.hpp"
#include <sys/wait.h>

using namespace std;

int Matrix_A[1500][1500] = {0};
int Matrix_B[1500][1500] = {0};
int Matrix_Ans[1500][1500] = {0};
int Scale=0;

void Gen_Matrix(int &hor, int &ver, int &hor1, int &ver1, int &hor2, int &ver2) //相承矩阵建立
{
    Get_Matrix(Matrix_A);
    Get_Matrix(Matrix_B);
    hor1 = Scale;
    ver1 = Scale;
    hor2 = Scale;
    ver2 = Scale;
    hor = hor1;
    ver = ver2;
}

int sub_martrix_mut(int H[], int L[][1500], int Lc, int cont) //A矩阵参加乘法的行，B矩阵，B矩阵参加乘法的列序号，行和列的元素个数（应相等）
{
    int sum = 0;
    for (int i = 0; i < cont; i++)
        sum += H[i] * L[i][Lc];
    return sum;
}

int main()
{
    clock_t begin,end;
    double cost;
    cout<<"请输入要计算矩阵的维度！"<<endl;
    cin>>Scale;
    begin=clock();
    pid_t fpid[1200]; //进程描述符
    int fd[1200][2];  //管道描述符
    int buf[1010] = {0};
    int HrLine1 = 0; //A矩阵的行数
    int VeLine1 = 0; //A矩阵的列数
    int HrLine2 = 0; //B矩阵的行数
    int VeLine2 = 0; //B矩阵的列数
    int HrLine = 0;  //结果矩阵的行数
    int VeLine = 0;  //结果矩阵的列数
    Gen_Matrix(HrLine, VeLine, HrLine1, VeLine1, HrLine2, VeLine2);
    // cout << "===================================================" << endl;
    // for (int i = 0; i < 30; i++)
    // {
    //     for (int j = 0; j < 30; j++)
    //         cout << Matrix_A[i][j] << "  ";
    //     cout << endl;
    // }
    // cout << "===================================================" << endl;
    // for (int i = 0; i < 30; i++)
    // {
    //     for (int j = 0; j < 30; j++)
    //         cout << Matrix_B[i][j] << "  ";
    //     cout << endl;
    // }
    // cout << "===================================================" << endl;
    for (int i = 0; i < HrLine; i++) //创建管道
        pipe(fd[i]);
    for (int i = 0; i < HrLine; i++)
    {
        fpid[i] = fork();
        if (fpid[i] == -1)
            cout << "Sub Process" << i << "error" << endl;
        else if (fpid[i] == 0) //利用子线程计算结果矩阵的i行的值
        {
            cout << "Loading Process" << i << endl;
            for (int j = 0; j < VeLine; j++)
            {
                buf[j] = sub_martrix_mut(Matrix_A[i], Matrix_B, j, VeLine1);
            }
            close(fd[i][0]);
            write(fd[i][1], buf, 8 * Scale);
            exit(0);
        }
    }

    wait(NULL);
    for (int i = 0; i < Scale; i++)
    {
        close(fd[i][1]);
        read(fd[i][0], Matrix_Ans[i], 8 * Scale);
    }
    end=clock();
    cout<<"计算完成，正在写入文件！"<<endl;
    Write_File(Matrix_Ans, Scale, Scale);
    cost=(double)(end-begin)/ CLOCKS_PER_SEC;
    cout<<"写入完成，程序耗时"<<cost<<endl;
    return 0;
}
